#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:HeWenjun
# datetime:2023/11/29 10:40
# software: PyCharm
import json
import time
from request_address_book import AddressBook

ad = AddressBook()
t = time.gmtime()


def org_code_modify():
    org_code_list = ['%23']
    complete_org_code_dict = {}
    """
    # 1、在循环中遍历列表org_code_list
    # 2、循环中会调用方法get_children_org_code()
    # 3、方法get_children_org_code()会返回一个新的列表
    # 4、将新列表内的值添加到旧列表org_code_list中
    # 5、继续遍历新的org_code_list
    # 6、保证循环会遍历列表org_list中所有的数据
    # 动态地扩充列表A并在遍历过程中访问新添加的元素
    """
    index = 0  # 初始化索引为0
    while index < len(org_code_list):
        item = org_code_list[index]
        # 1.调用方法，传入列表项作为参数
        # 2.接收返回参数，[完整的部门信息字典、存在下级组织的org_code列表]
        full_org_code_dict, parent_org_code_list = ad.get_children_org_code(item)
        # 将方法返回的新列表添加到原始列表A中
        org_code_list.extend(parent_org_code_list)
        # 将每次循环的所有部门信息字典合并
        complete_org_code_dict.update(full_org_code_dict)
        # 递增索引index以便在下一次循环中遍历新添加的元素
        index += 1
    print(len(complete_org_code_dict))
    # 按时间给新建文件命名
    file_name = time.strftime("%Y-%m-%d", t)
    with open(f'{file_name}组织列表.json', 'w', encoding='utf-8') as file:
        # 写入json文件时,顺便调整格式
        json.dump(complete_org_code_dict, file, indent=4, ensure_ascii=False)
        file.close()


def org_member_modify():
    re_dict = {}
    file_name = time.strftime("%Y-%m-%d", t)
    """获取org_code列表"""
    with open(f'{file_name}组织列表.json', 'r', encoding='utf-8') as org_code_file:
        org_code_dict = json.load(org_code_file)
        org_code_list = list(org_code_dict.keys())
        org_code_file.close()
    """新建org_member文件"""
    # org_code_list = ['17100000', '07215400']
    with open(f'{file_name}人员列表.json', 'w', encoding='utf-8') as org_member_file:
        """遍历org_code列表，逐个请求人员接口，将结果写入文档"""
        for org_code in org_code_list:
            print(org_code)
            re = ad.get_member_by_org_code(org_code=org_code)
            print(re)
            """重新组装了字典，以org_code作为键名，对应的人员信息作为键值"""
            re_dict[org_code] = re
        json.dump(re_dict, org_member_file, indent=4, ensure_ascii=False)
        org_member_file.close()


if __name__ == '__main__':
    print('start**************************')
    start_time = time.time()
    org_code_modify()
    org_member_modify()
    print('end*****************************')
    print('times = ', time.time() - start_time)
